<?php

defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );

class Cache {

	static function saveVar($name,$value) {
		$session = & JFactory::getSession('Database');
		$session->set($name,$value);
	}

	static function loadVar($name) {
		$session = & JFactory::getSession('Database');
		$value = $session->get($name);
		return $value;
	}

}

class Gdata {

	static $_auth = array(
	'username' => '',
	'password' => '',
	'authmode' => 'public',
	'authid' => ''
	);
	static $_albumPhotos = array();

	static function init($username,$password='',$authmode='') {

		if ($username) self::$_auth['username'] = $username;
		if ($password) self::$_auth['password'] = $password;
		if ($authmode) self::$_auth['authmode'] = $authmode;

		if (self::$_auth['authmode']!='public') {
			// To-do-possible: Google authentification -> get authid
		}

	}

	static function initPicasa($username,$password='',$authmode='',$thumbnailimgmax=160) {

		self::init($username,$password,$authmode);

		self::$_auth['thumbnailimgmax'] = ($thumbnailimgmax!='')?$thumbnailimgmax:160;
		global $mainframe;
		$params = &$mainframe->getParams();
		self::$_auth['imgmax'] = $params->get('fixedsize');
	}

	static function resetPicasaCache() {

		Cache::saveVar('pAlbumPhotos','');
		Cache::saveVar('pAlbumPhotosAlbumid','');
	}

	static function getPicasaAlbums($start=0,$length=0) {

		$xmldata = '';
		if ($xmldata=='') {

			$ch = curl_init("http://picasaweb.google.com/data/feed/api/user/" . self::$_auth['username']. '?thumbsize=' . self::$_auth['thumbnailimgmax'] . 'c');
			if (self::$_auth['authmode']!='public') {
				$header[] = 'Authorization: GoogleLogin auth='.$_auth['authid'];
				curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
				curl_setopt($ch, CURLOPT_HEADER, false);
			}
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$xmldata = curl_exec($ch);
			curl_close($ch);
		}

		$albumList = array();

		$numPhotos = 0;
		if(preg_match("@<\?xml version='1\.0' encoding='UTF-8'\?>@",$xmldata)) {

			$data = simplexml_load_string($xmldata);
			$namespace = $data->getDocNamespaces();

			foreach ($data->entry as $entry) {

				if (($numPhotos >= $start) && ($length==0 || ($numPhotos - $start)<$length)) {
					// collect for each album
					// - title
					// - url
					// - id

					// Gphoto namespace data
					$ns_gphoto = $entry->children($namespace['gphoto']);
					// Media namespace data
					$ns_media = $entry->children($namespace['media']);
					// Media thumbnail attributes
					$thb_attr = $ns_media->group->thumbnail->attributes();
					// Media content attributes
					$con_attr = $ns_media->group->content->attributes();

					$albumObject = 	array (
					'albumTitle' => (string)$entry->title,
					'photoURL' => (string)$con_attr['url'],
					'thumbURL' => (string)$thb_attr['url'],
					'albumID' => (string)$ns_gphoto->id
					);
					$albumList[] = $albumObject;

					$numPhotos += 1;
				}

			}

			// always reset album cache for allowing refresh from dynamic Picasa
			Cache::saveVar('AlbumPhotosAlbumid','');

		}

		return $albumList;
	}

	static function getPicasaAlbumphotos($albumid,$start=0,$length=0) {

		$incache = Cache::loadVar('AlbumPhotosAlbumid');
		$albumcache = Cache::loadVar('AlbumPhotos');
		global $mainframe;
		$params = &$mainframe->getParams();
		$imgmax=$params->get('fixedsize');
		if (!is_array($albumcache) || ($incache!=$albumid)) {

			$url = "http://picasaweb.google.com/data/feed/api/user/" . self::$_auth['username'] . '/albumid/' . $albumid . '?imgmax=' . $imgmax . '&thumbsize=' .self::$_auth['thumbnailimgmax'].'c';
			$ch = curl_init($url);
			if (self::$_auth['authmode']!='public') {
				$header[] = 'Authorization: GoogleLogin auth='.self::$_auth['authid'];
				curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
				curl_setopt($ch, CURLOPT_HEADER, false);
			}
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			$xmldata = curl_exec($ch);
			curl_close($ch);

			$numPhotos = 0; $albumTitle = ''; $photos = array();
			if (preg_match("@<\?xml version='1\.0' encoding='UTF-8'\?>@",$xmldata)) {

				$data = simplexml_load_string($xmldata);
				$namespace = $data->getDocNamespaces();

				$albumTitle = (string)$data->title[0];

				foreach ($data->entry as $entry) {

					// Collect for each photo;
					// - title
					// - url
					// - thumbnail url

					// Gphoto namespace data
					$ns_gphoto = $entry->children($namespace['gphoto']);
					// Media namespace data
					$ns_media = $entry->children($namespace['media']);
					// Media thumbnail attributes
					$thb_attr = $ns_media->group->thumbnail->attributes();
					// Media content attributes
					$con_attr = $ns_media->group->content->attributes();


					$photo = array (
					'photoTitle' => (string)$entry->title[0],
					'photoURL' => (string)$con_attr['url'],
					'Caption' => (string)$entry->summary,
					'thumbURL' => (string)$thb_attr['url']
					);
					$photos[] = $photo;

					$numPhotos += 1;
				}
			}

			$albumcache = array(
				'albumTitle' => $albumTitle,
				'numPhotos' => $numPhotos,
				'photosList' => $photos);


			// save for futher paging
			Cache::saveVar('AlbumPhotosAlbumid',$albumid);
			Cache::saveVar('AlbumPhotos',$albumcache);
		}

		// load specific page

		$photos = $albumcache['photosList'];
		$numPhotos = $albumcache['numPhotos'];
		if ($length==0 || ($start+$length)>$numPhotos) $length = $numPhotos - $start;
		$photoList = array();
		for ($i=$start;$i<($start + $length);$i++) {
			$photoList[] = $photos[$i];
		}

		$photoAlbum = array(
			'albumTitle' => $albumcache['albumTitle'],
			'numPhotos' => $numPhotos,
			'photosList' => $photoList);


		return $photoAlbum;
	}

}

class picasa2galleryModelpicasa2gallery extends JModel {

	function getPicasaUsername() {
		global $mainframe;
		$params = &$mainframe->getParams();
		$picasaUsername = $params->get('picasaUsername');
		return $picasaUsername;
	}

	function getMaxPhotosPerPage() {
		global $mainframe;
		$params = &$mainframe->getParams();
		$maxPhotosPerPage = $params->get('picasaMaxPhotosPerPage');
		return $maxPhotosPerPage;
	}

	function initGdata() {
		global $mainframe;
		$params = &$mainframe->getParams();
		$thumb = $params->get('picturethumbsize');
		if (empty($thumb)) $thumb = 150;
		$imgmax = $params->get('fixedsize');
		Gdata::initPicasa($this->getPicasaUsername(),'','', $thumb);
	}

	function getAlbumsList() {
		$this->initGdata();
		$albumsList = Gdata::getPicasaAlbums();
		Cache::saveVar('singleAbumView', '0');
		return $albumsList;
	}

	function getAlbum() {
		global $mainframe;
		$this->initGdata();
		$maxPhotosPerPage = $this->getMaxPhotosPerPage();
		$album = JRequest::getVar('album');
		$params = &$mainframe->getParams();
		if ($album=='') {
			$params = &$mainframe->getParams();
			$album =  $params->get('picasaalbumid');
			if ($album=='') {
				$albumsList = $this->getAlbumsList();
				if (is_array($albumsList) && count($albumsList)>0) {
					$album = $albumsList[0]['albumID'];
				}
			}
			JRequest::setVar('album', $album);
			Cache::saveVar('singleAbumView', '1');
		}
		$page = JRequest::getVar('page');
		if (!$page) {
			$page = 1;
			JRequest::setVar('page', $page);
		}
		// JOEL (all) $album = Gdata::getPicasaAlbumPhotos($album,$maxPhotosPerPage * ($page-1),$maxPhotosPerPage);
		$album = Gdata::getPicasaAlbumPhotos($album);
		return $album;
	}
	
	function getPicture() {
		global $mainframe;
		$this->initGdata();
		$album = JRequest::getVar('album');
		if ($album=='') {
			$params = &$mainframe->getParams();
			$album =  $params->get('picasaalbumid');
			if ($album=='') {
				$albumsList = $this->getAlbumsList();
				if (is_array($albumsList) && count($albumsList)>0) {
					$album = $albumsList[0]['albumID'];
				}
			}
		}
		$picture = JRequest::getVar('picture');
		if ($picture == '') $picture = 0;
		$album = Gdata::getPicasaAlbumPhotos($album, $picture, 1);
		return $album['photosList'][0];
	}
}